package com.ocom.company.controller;

import com.ocom.common.constant.CompanyServiceUrl;
import com.ocom.common.constant.UserConstants;
import com.ocom.common.dto.CompanyInfoDto;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.master.EntityCompanyList;
import com.ocom.common.entity.master.EntityCompanykeyInfo;
import com.ocom.common.entity.master.EntityWechatPerInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.company.feign.AccessClient;
import com.ocom.company.service.*;
import com.ocom.company.vo.GetCompanyInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class CompanyInfoController {
    private final Logger log = LoggerFactory.getLogger(CompanyInfoController.class);
    //注入 companyInfoService 业务层
    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private CompanyListInfoService companyListInfoService;

    @Autowired
    private AccessClient accessClient;

    @Autowired
    private CompanyKeyInfoService companyKeyInfoService;

    @Autowired
    private CompanyPartService companyPartService;


    @Autowired
    private WechatPerInfoService wechatPerInfoService;

    @Autowired
    MngUserInfoService mngUserInfoService;

    /**
     * 获取单位信息
     */
    @PostMapping(CompanyServiceUrl.URL_GetCompanyInfo)
    public Result GetCompanyInfo(@Validated @RequestBody GetCompanyInfoVo getCompanyInfoVo) {
        log.info("获取单位信息请求参数:{{}}",getCompanyInfoVo);
        return ResultUtil.success(companyInfoService.GetCompanyInfo(getCompanyInfoVo.getComId(), getCompanyInfoVo));
    }



    @PostMapping(CompanyServiceUrl.URL_getCompanyInfoById)
    public Result getCompanyInfoById(Long companyId){
        EntityCompanyInfo entityCompanyInfo=companyInfoService.getCompanyInfoById(companyId);
        if(entityCompanyInfo==null){
            return ResultUtil.error(ResultEnum.Err_302);
        }
        return ResultUtil.success(entityCompanyInfo);
    }


    /**
     * 添加单位
     */
    @PostMapping(CompanyServiceUrl.URL_AddCompanyInfo)
//        @GlobalTransactional //启动全局事务，只在第一个模块上添加
    public Result AddCompanyInfo(@Validated @RequestBody CompanyInfoDto companyInfo) {
        //判断comName是否已存在company_list.com_name (调用接口getCompanyListInfo)，
        // 不存在则进入下一步，存在则返回错误信息（1.单位名称已存在，请重新提交（2007））
        log.info("添加单位传参：{{}}",companyInfo);
        if ((UserConstants.NOT_UNIQUE.equals(companyInfoService.checkComNameUnique(companyInfo.getComName())))) {
            return ResultUtil.error(ResultEnum.Err_2007);
        }
        Long comId = companyPartService.GetComID();
        try {
            log.info("添加分库单位:{{}}",companyInfo);
            companyInfoService.AddCompanyInfo(companyInfo, comId);
        } catch (Exception exception) {
            log.error("添加分库单位失败：{{}}",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"添加单位失败");
        }
        Map<String, Object> map = new HashMap<>();
        try {
            log.info("添加总库单位:{{}}",companyInfo);
            map = companyListInfoService.AddCompanyListInfo(companyInfo);
        }catch (Exception exception){
            log.error("添加总库单位失败：{{}}",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"添加单位失败");
        }
           //7.调用接口 initCompanyPara 初始化门禁。
        try {
            accessClient.InitCompanyPara(companyInfo.getComId(), companyInfo.getCreateUserid(), comId);
        } catch (Exception exception) {
            log.error("初始化门禁失败：{{}}",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"初始化门禁失败");
        }
        //8.调用接口 addCompanyKeyInfo初始化单位秘钥。
        try {
            EntityCompanykeyInfo entityCompanykeyInfo = new EntityCompanykeyInfo();
            entityCompanykeyInfo.setComId(companyInfo.getComId());
            companyKeyInfoService.AddCompanyKeyInfo(entityCompanykeyInfo);
        } catch (Exception exception) {
            log.error("初始化单位秘钥失败：{{}}",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"初始化单位秘钥失败");
        }
        return ResultUtil.success(map);
    }

    /**
     * 更新单位信息
     */
    @PostMapping(CompanyServiceUrl.URL_UpdateCompanyInfo)
    public Result UpdateCompanyInfo(@Validated @RequestBody CompanyInfoDto companyInfo) {
        //判断comName是否已存在company_list.com_name (调用接口getCompanyListInfo)，
        // 不存在则进入下一步，存在则返回错误信息（1.单位名称已存在，请重新提交（2007））
        if (UserConstants.NOT_UNIQUE.equals(companyInfoService.checkComNameComId(companyInfo.getComName(), companyInfo.getComId()))) {
            return ResultUtil.error(ResultEnum.Err_2007);
        }
        try {
            companyInfoService.UpdateCompanyInfo(companyInfo, companyInfo.getComId());
        } catch (Exception exception) {
            exception.printStackTrace();
            return ResultUtil.error(ResultEnum.Err_2009);
        }
        Map<String, Object> map = companyListInfoService.UpdateCompanyListInfo(companyInfo);
        return ResultUtil.success(map);
    }

    /**
     * 3.5.获取普通用户单位信息列表(getCompanyInfoByUser)
     */

    @GetMapping(CompanyServiceUrl.URL_GetCompanyInfoByUser)
    public Result GetCompanyInfoByUser(String openid){
        //1.先根据传参条件查询表 wechat_per_info 得到集合 list1 ；
        if (StringUtils.isEmpty(openid)){
            return ResultUtil.error(ResultEnum.Err_203);
        }
        List<Object> list = new ArrayList<>();
        //1.先根据传参条件查询表 wechat_per_info 得到集合 list1 ；
        List<EntityWechatPerInfo> wechatPerInfos = wechatPerInfoService.getWechatPerInfo(openid);
        //2.根据list1.appid 判断openid为管理员用户还是普通用户，根据用户角色执行后续步骤。
        //普通用户：

        //根据list1.com_id查询表company_list as list2 (list1.com_id=list2.com_id) 得到 list2
        for (EntityWechatPerInfo wechatPerInfo: wechatPerInfos) {
       
            Map<Object, Object> map = new HashMap<>();
            EntityCompanyList companyList = companyListInfoService.getCompanyList(wechatPerInfo.getComId());
            if (companyList == null){
                continue;
            }
            map.put("comId",companyList.getComId());
            map.put("comName",companyList.getComName());
            map.put("color",companyList.getColor());
            map.put("version",3.0);
            map.put("pId",wechatPerInfo.getPId());
           list.add(map);
        }
      
        return ResultUtil.success(list);
    }
}
